import Taro from "@tarojs/taro";
import { Button, View } from "@tarojs/components";
import "./index.scss";
import { CustomRequest } from "@/utils/request";
import { hasPhoneYes } from "@/actions/hasPhone";
import { useState } from "react";
import { useDispatch } from "react-redux";

export interface IAvatarPermissionContainer {
  children: JSX.Element;
  reLaunchPath?: string;
}

export const PhonePermissionClickContainer = (
  props: IAvatarPermissionContainer
) => {
  const { children, reLaunchPath } = props;

  // const { params } = useRouter();

  const dispatch = useDispatch();

  // const hasPhone: boolean = useSelector((state: any) => state.hasPhone);

  const userInfo = Taro.getStorageSync("userInfo");

  const phone = userInfo ? userInfo.phone : "";

  const [userPhone, setUserPhone] = useState(phone);

  const getPhoneNumberCallback = (e: any) => {
    console.log(e)
    const code = Taro.getStorageSync('code')
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      CustomRequest.post("/api/user/user/login", {
        // encryptedData: e.detail.encryptedData,
        // iv: e.detail.iv,
        phoneCode: e.detail.code,
        code
        // token: Taro.getStorageSync("token"),
        // address: Taro.getStorageSync("city")
        //   ? Taro.getStorageSync("city")
        //   : "未授权",
        // scene: sceneFromOther
      })
        .then((res: any) => {
          if (res) {
            Taro.setStorageSync("phone", res.phoneNumber);
            setUserPhone(res.phoneNumber);
            dispatch(hasPhoneYes());
            if (reLaunchPath) {
              Taro.reLaunch({
                url: reLaunchPath
              });
              return;
            }
          }
        })
        .catch(_err => {
          Taro.showToast({
            title: "手机号授权失败,请稍后重试",
            icon: "none",
            duration: 2000
          });
        });
    }
  };
  return (
    <View className="phone-permission-container">
      {children}
      {!userPhone ? (
        <Button
          openType="getPhoneNumber"
          className="btn"
          onGetPhoneNumber={getPhoneNumberCallback}
        ></Button>
      ) : (
          ""
        )}
    </View>
  );
};
